importScripts('https://cdn.jsdelivr.net/npm/spark-md5/spark-md5.min.js')

globalThis.onmessage = async (e) => {
  const hash = await calculateMD5(e.data)
  globalThis.postMessage(hash)
}

function calculateMD5(chunks) {
  return new Promise((resolve) => {
    const startTime = performance.now() // 记录开始时间
    const spark = new SparkMD5.ArrayBuffer()
    const fileReader = new FileReader()

    fileReader.onload = (e) => {
      if (!e.target || !(e.target.result instanceof ArrayBuffer))
        return
      spark.append(e.target.result)
      const hash = spark.end()
      const endTime = performance.now() // 记录结束时间
      console.log(`calculateMD5 用时: ${(endTime - startTime) / 1000}  毫秒`)
      resolve(hash)
    }

    // 将所有分片合并成一个 Blob 对象
    const combinedBlob = new Blob(chunks)
    fileReader.readAsArrayBuffer(combinedBlob)
  })
}
